package com.xxh.dasongapp.security.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;

public class JwtUtil {
    //密钥
    private static final String SECRET = "44190019991228277X";
    //请求头
    private static final String HEADER = "Authorization";
    //请求尾
    private static final String PREFIX = "Bearer";
    //签发者
    private static final String ISS = "admin";

    // 角色的key
    private static final String ROLE = "role";

    // openId的key
    private static final String OPENID = "openid";

    //有效时间是3600秒，既是1个小时
    private static final long EXPIRATION = 3600L;



    public static String createToken(String username,String role,String openId){
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE, role);
        map.put(OPENID, openId);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
    }

    // 从token中获取用户名
    public static String getUsername(String token){
        return getTokenBody(token).getSubject();
    }

    // 获取用户角色
    public static String getUserRole(String token){
        return (String) getTokenBody(token).get(ROLE);
    }


    //获取openid
    public static String getOpenId(String token){return (String) getTokenBody(token).get(OPENID);}

    //解密token内容
    public static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }


    // 判断JWT是否过期
    public static boolean isTokenExpired(String token) {
        Claims claims = getTokenBody(token);
        return claims.getExpiration().before(new Date());
    }

    public static String getHeader(){
        return HEADER;
    }



}

